﻿using System;
using System.Collections.Generic;
using System.Linq;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Newtonsoft.Json;
using static CoreShop.Services.PosRemoteServices;
using Yitter.IdGenerator;
using CoreShop.Model.FromBody;
using CoreShop.App.Units.Interface;
using System.Threading.Tasks;
using CoreShop.Model.ViewModels;
using NPOI.SS.Formula.Functions;

namespace CoreShop
{
    public class OrderRefundUtil
    {
        public static async Task<bool> SetRefundPayment(UIForm uIForm, OrderRefundPost orderRefund)
        {
            var mobilePays = orderRefund.orderPayment.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.alipay
            || p.paymentId == (int)GlobalEnumVars.Payment.wechatpay || p.paymentId == (int)GlobalEnumVars.Payment.bank).ToList();

            if ((mobilePays != null) && (mobilePays.Count > 0))
            {
                var refundPayTime = AppConstVars.systemsetup.refundPayTime;
                DateTime dPOSTime = orderRefund.orderMaster.orderDate;
                DateTime dDateNow = DateTime.Now;
                TimeSpan timeSpan = dDateNow - dPOSTime;
                double hPosPayTime = timeSpan.TotalMinutes;
                if ((hPosPayTime < refundPayTime) && (refundPayTime > 0))
                {
                    if (!uIForm.ShowAskDialog("有移动支付，要原路退款并反退货吗？")) return false;
                    string msg = "";
                    var moblePayment = mobilePays.First();
                    var orderPayment = new OrderPaymentPost()
                    {
                        orderId = moblePayment.paymentCode.ToString(),
                        payAmount = moblePayment.payAmount
                    };
                    bool bResult = PaymentUtil.SetRefundMobilePay(orderPayment, ref msg);
                    if (!bResult) UIMessageBox.Show(msg, "提示:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return bResult;
                }
                else
                {
                    UIMessageBox.Show("有移动支付的单据，必须在规定时间内退单！。", "移动支付退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                    return false;
                }
            }
            return await SetRefundMemberPay(orderRefund);
        }
        public static async Task<bool> SetRefundMemberPay(OrderRefundPost orderRefund)
        {
            //上传退款数据
            var userId = CommFunc.ConvertToBigInt(orderRefund.orderMaster.userId);
            if (userId == 0) return true;
            var member = await MemberApiUtil.GetListVipInfoById(userId);
            if (member == null)
            {
                UIMessageBox.Show("有会员支付，但未找到相应的会员资料！。", "会员支付退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }           

            var memberPays = orderRefund.orderPayment.Where(p => p.paymentId == (int)GlobalEnumVars.Payment.balancepay).ToList();
            if ((memberPays == null) || (memberPays.Count == 0)) return true;
            var memberPay = memberPays.First();

            var balanceServices = new corecmsuserbalanceServices();
            long sourceId = CommFunc.ConvertToBigInt(memberPay.paymentCode);
            var balance = balanceServices.GetById(sourceId);
            if (balance == null)
            {
                UIMessageBox.Show("未找到要退款的会员支付订单！。", "会员支付退款出错:", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }

            var payRs = await MemberApiUtil.VipRefund(long.Parse((memberPay.payAmount * 100).ToString("f0")), PAYTYPE.BALANCE, CommonHelper.GetMchNo(AppConstVars.sysStore.deviceId), memberPay.mchNo, AppConstVars.sysStore.branchId);
            if (payRs.code != 200)
            {
                UIMessageBox.Show("VipRefund 退款失败！。", "会员支付退款出错:" + payRs.msg, UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }

            var payRsData = JsonConvert.DeserializeObject<VipPayResultDto>(payRs.data.ToString());
            orderRefund.orderMaster.userOldPoint = CommFunc.ConvertToInt32(member.point);
            orderRefund.orderMaster.userNewPoint = CommFunc.ConvertToInt32(member.point) - orderRefund.orderMaster.userPoint;
            orderRefund.orderMaster.userOldBalance = payRsData.beforeAmount;
            orderRefund.orderMaster.userNewBalance = payRsData.afterAmount;

            balance.id = CommFunc.GetCorpNextId(AppConstVars.sysUser.corpId, YitIdHelper.NextId());
            balance.orderId = CommonHelper.GetSerialNumberType((int)GlobalEnumVars.SerialNumberType.会员充值消费编号);
            balance.userId = userId;
            balance.type = (int)GlobalEnumVars.UserBalanceTypes.ConsumeRefund;
            balance.storeId = AppConstVars.sysUser.storeId;
            balance.money = -memberPay.payAmount;
            balance.giftAmount = 0;
            balance.balance = 0;
            balance.giftBalance = 0;
            balance.sourceId = sourceId;
            balance.memo = "会员消费退款";
            balance.createTime = DateTime.Now;
            balance.corpId = AppConstVars.sysUser.corpId;
            balance.cardItemId = 0;
            balance.quantity = 0;
            balance.balanceQuantity = 0;
            balance.sysUserId = AppConstVars.sysUser.id;
            balance.paymentId = (int)GlobalEnumVars.Payment.balancepay;
            balance.paymentCode = "";
            balance.payStatus = (int)GlobalEnumVars.OrderPayStatus.UnPay;
            balance.status = (int)GlobalEnumVars.BalanceStatus.UnCheck;

            if (balanceServices.InsertAsync(balance))
            {
                string msg = "";
                return true;
            }
            else
            {
                UIMessageBox.Show("会员余额退款失败", "系统提示", UIStyle.Red, UIMessageBoxButtons.OK);
                return false;
            }
        }
    }
}
